﻿using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;

namespace Commnunications
{
    public class TcpHandle : ChannelHandle
    {
        /// <summary>
        /// tcp连接对象
        /// </summary>
        /// <param name="socket"></param>
        public TcpHandle(Socket socket) : base(ChannelHandleType.Tcp)
        {
            Net = socket;
        }
        /// <summary>
        /// 判断是否连接ok
        /// </summary>
        public override bool IsConnected
        {
            get
            {
                return Net != null && Net.Connected;
            }
        }
        /// <summary>
        /// 发送
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public override int Send(byte[] buffer)
        {
            return Net.Send(buffer);
        }
        /// <summary>
        /// 接收对象
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="len"></param>
        /// <returns></returns>
        public override int Receive(byte[] buffer, int len)
        {
            return Net.Receive(buffer, len, SocketFlags.None);
        }
        /// <summary>
        /// udp
        /// </summary>
        public Socket Net
        {
            get => _socket;
            private set
            {
                _socket = value;
            }
        }
        Socket _socket;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ip">ip或串口号</param>
        /// <param name="conTimeout">连接超时;串口时，忽略该参数</param>
        /// <param name="port">串口时，忽略该参数</param>
        /// <param name="readWriteTimeout">tcp 该参数大于0时设定；读写超时</param>
        /// <returns></returns>
        public override bool Connect(string ip, int conTimeout = 5000, int port = 0, int readWriteTimeout = 5000)
        {
            var isOk= ChannelFactory.ConnectAsync(ip, port, conTimeout, ref _socket);
            if (isOk&&readWriteTimeout>0)
            {
                _socket.ReceiveTimeout = _socket.SendTimeout = readWriteTimeout;
            }
            return isOk;
        }
        public override void Close()
        {
            if (_socket != null)
            {
                _socket.Close();
                _socket = null;
            }
        }
    }
}
